package com.frank.circle.controller;

import com.frank.circle.entity.ShareCircle;
import com.frank.circle.req.SaveCircleReq;
import com.frank.circle.req.UpdateCircleReq;
import com.frank.circle.service.CircleService;
import com.frank.circle.vo.CircleVo;
import com.frank.common.entity.Result;
import com.google.common.base.Preconditions;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @author Frank Zou
 * @version v0.0.1
 * @date 2025/10/15
 * @description
 */
@RestController
public class CircleController {


    private final CircleService circleService;

    public CircleController(CircleService circleService) {
        this.circleService = circleService;
    }

    /**
     * list all circles
     * @return result
     */
    @GetMapping("/list")
    public Result<List<CircleVo>> listCircle(){
        return Result.ok(circleService.listCircle());
    }


    /**
     * save a new circle
     * @param req save circle request
     * @return result
     */
    @PostMapping("/save")
    public Result<Boolean> saveCircle(@RequestBody SaveCircleReq req){
        Preconditions.checkArgument(StringUtils.isNotBlank(req.getCircleName()), "Circle name is not null");
        Preconditions.checkArgument(StringUtils.isNotBlank(req.getIcon()), "Circle icon is not null");

        if (!Objects.equals(req.getParentId(), -1L)){
            ShareCircle shareCircle = circleService.findOne(req.getParentId());
            Preconditions.checkNotNull(shareCircle, "Parent circle 不存在！");
        }
        return Result.ok(circleService.saveCircle(req));
    }

    /**
     * update a circle
     * @param req update circle request
     * @return result
     */
    @PutMapping("/update")
    public Result<Boolean> updateCircle(@RequestBody UpdateCircleReq req){
        Preconditions.checkArgument(Objects.nonNull(req.getId()), "Circle id is not null");
        Preconditions.checkArgument(StringUtils.isNotBlank(req.getIcon()), "Circle icon is not null");
        Preconditions.checkArgument(StringUtils.isNotBlank(req.getCircleName()), "Circle name is not null");

        if (!Objects.equals(req.getParentId(), -1L)){
            ShareCircle shareCircle = circleService.findOne(req.getParentId());
            Preconditions.checkNotNull(shareCircle, "Parent circle 不存在！");
        }
        return Result.ok(circleService.updateCircle(req));
    }

    /**
     * delete a circle
     * @param id circle id
     * @return result
     */
    @DeleteMapping("/delete")
    public Result<Boolean> deleteCircle(Long id){
        Preconditions.checkArgument(Objects.nonNull(id), "Circle id is not null");
        return Result.ok(circleService.deleteCircle(id));
    }


}
